package com.picshare.interceptor;

import com.picshare.service.ApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Component
public class ApiKeyInterceptor implements HandlerInterceptor {
    
    @Autowired
    private ApiService apiService;
    
    // 不需要API Key验证的路径
    private static final List<String> EXCLUDE_PATHS = Arrays.asList(
        "/api/client/login",
        "/api/client/health",
        "/api/client/apikey/generate"
    );
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String path = request.getRequestURI();
        
        // 检查是否在排除列表中
        if (EXCLUDE_PATHS.stream().anyMatch(path::startsWith)) {
            return true;
        }
        
        // 只对客户端API路径进行验证
        if (path.startsWith("/api/client/")) {
            String apiKey = request.getHeader("X-API-Key");
            
            if (apiKey == null || !apiService.validateApiKey(apiKey)) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setContentType("application/json");
                response.getWriter().write("{\"success\":false,\"message\":\"API Key无效或缺失\"}");
                return false;
            }
        }
        
        return true;
    }
}